package com.chinatgl.latte.ec.main.index._1;

import android.content.Context;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chinatgl.latte.app.Latte;
import com.chinatgl.latte.delegates.BaseFragment;
import com.chinatgl.latte.ec.API;
import com.chinatgl.latte.ec.R;
import com.chinatgl.latte.ec.R2;
import com.chinatgl.latte.ec.contains.Contains;
import com.chinatgl.latte.ec.mode.AD;
import com.chinatgl.latte.ec.params.MapUtil;
import com.chinatgl.latte.net.NetRequest;
import com.chinatgl.latte.net.listener.onNetRquestListener;
import com.chinatgl.latte.ui.recycleView.FullyGridLayoutManager;
import com.chinatgl.latte.ui.recycleView.MyRecyclerView;
import com.chinatgl.latte.util.json.Result;
import com.google.gson.reflect.TypeToken;
import com.paojiao.recyclerviewanimators.FadeInAnimator;
import com.paojiao.recyclerviewanimators.adapters.AlphaInAnimationAdapter;
import com.paojiao.recyclerviewanimators.adapters.ScaleInAnimationAdapter;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.WeakHashMap;

import cn.iwgang.countdownview.CountdownView;


/**
 * Created by Administrator on 2017/4/24.
 * 首页中的第一个界面
 * 1. 首界面上最上面的是一个轮播图
 * 2. 加上一个recycleView
 * 3. 加上一个recycleView加上一个头部 头部的组成是轮播图 轮播文字 还有三个图片
 * 4. 页面上暂时有一个bug 关于轮播文字处理的这一块
 */
@SuppressWarnings("all")
public class MYHomeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {
    private SwipeRefreshLayout refreshLayout;
    private RecyclerView recyclerview;
    private ArrayList<AD> mDatas = new ArrayList<AD>();
    private RecyclerViewHFAdapter adapter;
    private Banner convenientBanner;
    private LinearLayout linearlayout;
    private LinearLayout homeGridLayout;
    private List<String> networkImages;
    private ScaleInAnimationAdapter scaleAdapter;
    private double lastTimeMillis;
    private CountdownView countdownview;
    private MyRecyclerView recyclerview_horizontal;
    private TextView tvQianggouMore;
    private RelativeLayout rl_recommend;
    private RelativeLayout rl_group_purchase;
    private ImageView ivGototop;
    private int pageNo = 1;
    private boolean isGetMore = true;


    @Override
    public CharSequence getTitle() {
        return "首页";
    }

    @Override
    public Object getContentView() {
        return R.layout.fragment_home_home;
    }

    @Override
    public void initView() {
        //刷新控件
        refreshLayout = (SwipeRefreshLayout) findView(R.id.refreshLayout);
        ivGototop = findView(R.id.iv_gototop);

        //头布局
        linearlayout = (LinearLayout) LayoutInflater.from(getActivity()).inflate(R.layout.home_header, null);
        //轮播图
        convenientBanner = (Banner) linearlayout.findViewById(R.id.conveninbanner);
        //轮播文字
        // autoText = (AutoTextView) linearlayout.findViewById(R.id.autoText);
        //限时抢购的商品列表
        recyclerview_horizontal = (MyRecyclerView) linearlayout.findViewById(R.id.id_recyclerview_horizontal);
        //GridLayout
        homeGridLayout = (LinearLayout) linearlayout.findViewById(R.id.home_gridview);
        //倒计时
        countdownview = (CountdownView) linearlayout.findViewById(R.id.cv_countdownView);
        //抢购 > 更多
        tvQianggouMore = (TextView) linearlayout.findViewById(R.id.tv_qianggou_more);
        //推荐
        rl_recommend = (RelativeLayout) linearlayout.findViewById(R.id.rl_recommend);
        //团购
        rl_group_purchase = (RelativeLayout) linearlayout.findViewById(R.id.rl_group_purchase);

        // 下面的专题的  recyclerview 控件
        recyclerview = (RecyclerView) findView(R.id.recyclerView);
        //设置专题的列表
        recyclerview.setHasFixedSize(true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        recyclerview.setLayoutManager(layoutManager);

        recyclerview.setItemAnimator(new FadeInAnimator());
        adapter = new RecyclerViewHFAdapter(getActivity(), mDatas); //这个时候 里面的集合是空的
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(adapter);
        scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
        recyclerview.setAdapter(scaleAdapter);
        //添加头部的布局
        adapter.addHeader(linearlayout);

    }

    @Override
    public void initListener() {
        refreshLayout.setOnRefreshListener(this);

        recyclerview.setOnScrollListener(new OnRcvScrollListener() {

            private int totalDy;

            @Override
            public void onBottom() {
                super.onBottom();
                System.out.println("底部");
                //加载更多
                onLowMemory();
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                totalDy += dy;
                if (totalDy > 2000) {
                    //显示
                    ivGototop.setVisibility(View.VISIBLE);
                } else {
                    //隐藏
                    ivGototop.setVisibility(View.GONE);
                }
            }
        });


        tvQianggouMore.setOnClickListener(this);
        //推荐
        rl_recommend.setOnClickListener(this);
        //团购
        rl_group_purchase.setOnClickListener(this);

        ivGototop.setOnClickListener(this);

    }

    /*
    加载数据
    * */
    private void loadinitDatas() {

        WeakHashMap<String, Object> params = MapUtil.getParams();

        params.put("code", Contains.INDEX_SUB);
        params.put("pageNo", String.valueOf(pageNo));
        params.put("pageSize", "12");
        Type type = new TypeToken<Result<List<AD>>>() {
        }.getType();
        //时间的单位是分钟
        NetRequest.post(API.ADVLIST, params, type, true, 60, new onNetRquestListener() {
            @Override
            public void requestdataFinish(String catalog, Object bean) {
                if (bean != null) {
                    if (bean instanceof String) {
                        Toast.makeText(Latte.getApplication(), "网络异常,请稍后再试", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Result<List<AD>> result = (Result<List<AD>>) bean;
                    if (result.getCode() == 0) {
                        List<AD> result1 = result.getResult();
                        if (result1 != null && result1.size() > 0) {
                            if (pageNo == 1) {
                                mDatas.clear();
                            }
                            mDatas.addAll(result1);

                        } else if (result1 == null || result1.size() < 12) {
                            isGetMore = false;
                        }
                    }
                    refreshLayout.setRefreshing(false);
                    scaleAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void requestdataFailed(String msg, Throwable e) {

            }

            @Override
            public void requestComplete() {


            }
        },getActivity());
    }

    //轮播图图片
    private String[] images;

    @Override
    public void initData() {
        stateLayout.showContentView();
        //设置布局管理器
        FullyGridLayoutManager linearLayoutManager = new FullyGridLayoutManager(context, 1);
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        linearLayoutManager.setSmoothScrollbarEnabled(true);
        recyclerview_horizontal.setLayoutManager(linearLayoutManager);
        final List<String> strings = new ArrayList<>();
        for (int i = 0; i < 4; i++) {
            strings.add("暂无报价");
        }
        setconvenientBanner();

        loadinitDatas();//加入 数据
    }

    private void setconvenientBanner() {
        //轮播图的设置 网络请求的数据 POST /mobi/adv/list
        WeakHashMap<String, Object> params = MapUtil.getParams();
        params.put("code", Contains.INDEX_IMAGES);
        params.put("pageNo", "1");
        params.put("pageSize", "30");

        Type type = new TypeToken<Result<List<AD>>>() {
        }.getType();

        NetRequest.post(API.ADVLIST, params, type, true, 60, new onNetRquestListener() {
            @Override
            public void requestdataFinish(String catalog, Object bean) {
                if (bean != null) {
                    if (bean instanceof String) {

                        return;
                    }
                    Result<List<AD>> result = (Result<List<AD>>) bean;
                    if (result.getCode() == 0) {
                        List<AD> result1 = result.getResult();
                        if (result1 != null && result1.size() > 0) {
                            setBannerDatas(result1);
                        }
                    }
                }
            }

            @Override
            public void requestdataFailed(String msg, Throwable e) {

            }

            @Override
            public void requestComplete() {

            }
        },getActivity());

    }


    /***
     * 加载更多
     */
    @Override
    public void onLowMemory() {
        super.onLowMemory();

        if (isGetMore) {
            pageNo++;
            if (refreshLayout.isRefreshing() != true) {
                loadinitDatas();
            }
        }


    }

    /***
     * 刷新
     */
    @Override
    public void onRefresh() {
        System.out.println("加载更多");
            pageNo = 1;
            loadinitDatas();
            countdownview.restart();


    }


    //如果你需要考虑更好的体验，可以这么操作
    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        convenientBanner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        convenientBanner.stopAutoPlay();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R2.id.tv_qianggou_more:
                System.out.println("=====tv_qianggou_more======");
                break;

            case R2.id.rl_recommend:
                //推荐
                System.out.println("====rl_recommend推荐=======");

                break;
            case R2.id.rl_group_purchase:
                System.out.println("=====rl_group_purchase======");

                break;
            case R2.id.iv_gototop:
                recyclerview.scrollToPosition(0);

                ivGototop.setVisibility(View.GONE);
                break;
        }
    }


    private void setBannerDatas(final List<AD> result1) {
        networkImages = new ArrayList<>();
        for (int i = 0; i < result1.size(); i++) {
            AD ad = result1.get(i);
            String image = ad.getImage();
            networkImages.add(image);
        }

        //广告轮播图
        convenientBanner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        convenientBanner.setImageLoader(new ImageLoader() {


            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                Glide.with(context).load(path).placeholder(R.mipmap.img_zhanwei_banner).into(imageView);
            }
        });
        convenientBanner.setImages(networkImages);
        //设置banner动画效果
        convenientBanner.setBannerAnimation(Transformer.Default);
        //设置自动轮播，默认为true
        convenientBanner.isAutoPlay(true);
        //设置轮播时间
        convenientBanner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        convenientBanner.setIndicatorGravity(BannerConfig.CENTER);


        //banner设置方法全部调用完毕时最后调用
        convenientBanner.start();
        convenientBanner.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                AD ad = result1.get(position);

                switch (ad.getType()) {

                    case "0"://图片


                        break;
                    case "1"://单品


                        break;
                    case "2"://专题


                        break;
                    case "3"://网页


                        break;
                }


            }
        });


    }
}
